import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { TransformInterceptor } from './system/filter/transform.interceptor';
import { appConfig } from './config/config';
// import { HttpExceptionFilter } from './system/filter/http-exception.filter';
// import * as csurf from 'csurf';
import helmet from 'helmet';
import { WsAdapter } from './system/socket/ws-adapter';
import { AllExceptionsFilter } from './system/filter/any-exception.filter';
import { Logger } from './system/utils/log4js/log4js';
// import { logger } from './system/utils/log4js/log.middleware';
import * as express from 'express';
// import { RolesGuard } from './system/auth/roles.guard';
// 热重载
declare const module: any;
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    // logger: Logger,
  });
  // const logger = new Logger();
  // application/json 解析
  app.use(express.json());
  // 解析 application/x-www-form-urlencoded
  app.use(express.urlencoded({ extended: true }));
  // app.use(logger);
  // 管道
  app.useGlobalPipes(new ValidationPipe());
  // 全局注册错误的过滤器
  // app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalFilters(new AllExceptionsFilter());
  // 拦截器
  app.useGlobalInterceptors(new TransformInterceptor());
  // 角色
  // app.useGlobalGuards(new RolesGuard());
  // 跨域
  app.enableCors();
  // 防web常见漏洞
  app.use(
    helmet({
      // contentSecurityPolicy: {
      //   directives: {
      //     defaultSrc: [`'self'`],
      //     styleSrc: [`'self'`, `'unsafe-inline'`],
      //     imgSrc: [`'self'`, 'data:', 'validator.swagger.io'],
      //     scriptSrc: [`'self'`, `https: 'unsafe-inline'`],
      //   },
      // },
      contentSecurityPolicy: false,
    }),
  );
  // CSRF保护
  // app.use(csurf());
  // 使用websocket
  if (appConfig.socketStatus) app.useWebSocketAdapter(new WsAdapter(app));
  const port = process.env.SERVICE_PORT;
  // swagger
  const options = new DocumentBuilder()
    .addBearerAuth()
    .setTitle(appConfig.serverName)
    .setDescription(appConfig.description)
    .setVersion(appConfig.version)
    // .addTag(appConfig.tag)
    // .addServer(appConfig.apiPath)
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup(appConfig.apiDocsPath, app, document);
  await app.listen(port);
  Logger.log(
    `"${appConfig.serverName}" application is running.\n\thttp://127.0.0.1:${port}/${appConfig.apiDocsPath}`,
  );
  // 热重载
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}
bootstrap().then();
